package com.smart.community.region.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.region.entity.ZoneDrawing;
import com.smart.community.region.mapper.ZoneDrawingMapper;
import com.smart.community.region.service.IZoneDrawingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 分区绘图数据服务实现类
 *
 * @author Wu.Liang
 * @since 2025-01-30
 */
@Slf4j
@Service
public class ZoneDrawingServiceImpl extends ServiceImpl<ZoneDrawingMapper, ZoneDrawing> implements IZoneDrawingService {

    @Override
    @Cacheable(value = "zone:drawing", key = "'current:' + #communityId", unless = "#result == null")
    public ZoneDrawing getByCommunityId(Long communityId) {
        long startTime = System.currentTimeMillis();
        log.info("根据社区ID查询绘图数据，社区ID: {}", communityId);
        
        // 参数验证
        if (communityId == null) {
            log.warn("社区ID不能为空");
            return null;
        }
        
        try {
            LambdaQueryWrapper<ZoneDrawing> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZoneDrawing::getCommunityId, communityId)
                       .eq(ZoneDrawing::getIsCurrent, SystemStatusEnum.ENABLED.getCode())
                       .last("LIMIT 1");
            
            ZoneDrawing result = this.getOne(queryWrapper);
            long endTime = System.currentTimeMillis();
            log.info("根据社区ID查询绘图数据完成，社区ID: {}，结果: {}，耗时: {}ms", 
                    communityId, result != null ? "找到" : "未找到", (endTime - startTime));
            
            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("根据社区ID查询绘图数据失败，社区ID: {}，耗时: {}ms，错误: {}", 
                    communityId, (endTime - startTime), e.getMessage());
            return null;
        }
    }

    @Override
    @Cacheable(value = "zone:drawing", key = "'all:' + #communityId", unless = "#result == null || #result.isEmpty()")
    public List<ZoneDrawing> getAllByCommunityId(Long communityId) {
        long startTime = System.currentTimeMillis();
        log.info("根据社区ID查询所有绘图数据，社区ID: {}", communityId);
        
        // 参数验证
        if (communityId == null) {
            log.warn("社区ID不能为空");
            return Collections.emptyList();
        }
        
        try {
            LambdaQueryWrapper<ZoneDrawing> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZoneDrawing::getCommunityId, communityId)
                       .orderByDesc(ZoneDrawing::getVersion);
            
            List<ZoneDrawing> result = this.list(queryWrapper);
            long endTime = System.currentTimeMillis();
            log.info("根据社区ID查询所有绘图数据完成，社区ID: {}，结果数量: {}，耗时: {}ms", 
                    communityId, result.size(), (endTime - startTime));
            
            return result != null ? result : Collections.emptyList();
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("根据社区ID查询所有绘图数据失败，社区ID: {}，耗时: {}ms，错误: {}", 
                    communityId, (endTime - startTime), e.getMessage());
            return Collections.emptyList();
        }
    }

    @Override
    @CacheEvict(value = "zone:drawing", allEntries = true)
    public int updateByCommunityId(Long communityId, ZoneDrawing drawing) {
        long startTime = System.currentTimeMillis();
        log.info("根据社区ID更新绘图数据，社区ID: {}", communityId);
        
        // 参数验证
        if (communityId == null) {
            log.warn("社区ID不能为空");
            return 0;
        }
        if (drawing == null) {
            log.warn("绘图数据不能为空");
            return 0;
        }
        
        try {
            // 先删除旧的当前版本
            LambdaQueryWrapper<ZoneDrawing> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(ZoneDrawing::getCommunityId, communityId)
                        .eq(ZoneDrawing::getIsCurrent, SystemStatusEnum.ENABLED.getCode());
            this.remove(deleteWrapper);
            
            // 插入新版本
            drawing.setCommunityId(communityId);
            drawing.setIsCurrent(SystemStatusEnum.ENABLED.getCode());
            boolean success = this.save(drawing);
            
            int result = success ? 1 : 0;
            long endTime = System.currentTimeMillis();
            log.info("根据社区ID更新绘图数据完成，社区ID: {}，结果: {}，耗时: {}ms", 
                    communityId, success ? "成功" : "失败", (endTime - startTime));
            
            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.warn("根据社区ID更新绘图数据失败，社区ID: {}，耗时: {}ms，错误: {}", 
                    communityId, (endTime - startTime), e.getMessage());
            return 0;
        }
    }
}
